<template>
	<view class="home">
		<view v-if="petDataList.length !== 0">
			<view class="loadingState" v-show="loadState">
				<u-skeleton
					rows="3"
					avatar
					title
					loading
				></u-skeleton>
			</view>
			<view class="card">
				<view class="item" v-for="item in petDataList">
					<pet-item :item="item"></pet-item>
				</view>
			</view>
			<view class="add">
				<u-icon
					size="30"
					name="plus"
					color="#fff"
					@click="jumpToCreate"
				></u-icon>
			</view>
		</view>
		<view v-else>
			<!-- 写一个新建宠物的按钮，圆形，在屏幕中间居中显示-->
			<button class="addPet" @click.native="jumpToCreate()">新建宠物</button>
		</view>
	</view>
</template>

<script>
	import {
		getConstellation,
		getCalculateMonthAge,
		getDaysArrived,
	} from "@/utils/tools.js";
	
	const db = uniCloud.database(); // 联通数据库
	
	export default {
		data() {
			return {
				petDataList:[],
				loadState: false,
				localId: {}
			}
		},
		onLoad() {
			this.getId();
			this.getPetData();
		},
		methods: {
			getId() {
				const currentUser = uni.getStorageSync("uni-id-pages-userInfo")
				this.localId = currentUser._id;
			},
			getPetData() {
				let petTemp = db.collection("pet_information")
					.where({
						user_id: this.localId
					})
					.field("user_id, avatar_file, name, petType, petKind, sex, birthday, arriveTime")
					.getTemp();
				let userTemp = db.collection("uni-id-users")
					.field("_id")
					.getTemp();
					
				db.collection(petTemp, userTemp)
					.get()
					.then(res => {
						this.petDataList = res.result.data;
						// 给petDataList增加一对key：value
						this.petDataList.forEach((item, index) => {
							this.petDataList[index].constellation = getConstellation(item.birthday); // 映射生日为星座
							this.petDataList[index].calculateMonthAge = getCalculateMonthAge(item.birthday); // 通过生日计算月龄
							this.petDataList[index].dayArrived = getDaysArrived(item.arriveTime); // 通过到家日计算陪伴天数
						})
						console.log(this.petDataList);
					})
			},
			jumpToCreate() {
				uni.navigateTo({
					url: "/pages/addPet/addPet"
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.home{
	.loadingState {
		padding: 30rpx;
	}
	.card {
		.item {
		}
	}
	.add {
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 0 10rpx rgba(1, 153, 254, 0.6);
		width: 120rpx;
		height: 120rpx;
		background: #3c9cff;
		border-radius: 50%;
		color: #fff;
		position: fixed;
		z-index: 100;
		bottom: 150rpx;
		right: 50rpx;
	}
	.addPet {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%,-50%);
	}
}
	
</style>
